/**
 * desc: 添加联系人

 */

import React, { useEffect, useState } from 'react';
import CommonModal from '@/components/CommonModal';
import CommonLoading from '@/components/CommonLoading';
import { Form, Input, message, Select, Tooltip } from 'antd';
import { queryNoticeList, savePersonUpdate } from '../service';
import { isEmpty, find } from 'lodash';
import { mobile } from '@/utils/rule';

const { Option } = Select;

const layout1 = {
  //发布表单排布
  labelCol: {
    span: 6,
  },
  wrapperCol: {
    span: 14,
  },
};

const AddUserModal = ({ visible, item, handleOk, handleCancel }) => {
  const [loading, setLoading] = useState(false);
  const [userList, setUserList] = useState([]); //可能得提醒联系人列表

  const [form] = Form.useForm();

  const account = Form.useWatch('account', form);

  useEffect(() => {
    if (visible) {
      form.resetFields();
      getPersonList();
    }
  }, [visible]);

  useEffect(() => {
    if (account) {
      const item = find(userList, ['id', account]);
      form.setFieldsValue({
        name: item?.name,
        phone: item?.mobile,
      });
    } else {
      form.setFieldsValue({
        name: undefined,
        phone: undefined,
      });
    }
  }, [account]);

  //查询可能得提醒联系人列表
  const getPersonList = async () => {
    setLoading(true);
    const { success, data = [] } = await queryNoticeList();
    if (success) {
      setUserList(data);
    }
    setLoading(false);
  };

  const onOk = () => {
    form.validateFields().then((val) => {
      handleSubmit(val);
    });
  };

  const handleSubmit = async (val) => {
    const { phone, name } = val;
    setLoading(true);
    const params = {
      name,
      phone,
      noticeId: item.id,
    };
    const { success } = await savePersonUpdate(params);
    setLoading(false);
    if (success) {
      message.success('修改成功');
      handleOk();
    }
  };

  const options =
    !isEmpty(userList) &&
    userList.map((d) => (
      <Option value={d.id} key={d.id} label={d.account}>
        <Tooltip title={d.account}>{d.account}</Tooltip>
      </Option>
    ));

  return (
    <CommonModal
      title="添加联系人"
      visible={visible}
      onCancel={handleCancel}
      width="500px"
      onOk={onOk}
    >
      <Form form={form} name="add-user-modal" {...layout1} initialValues={{}}>
        <Form.Item label="账号" name="account">
          <Select allowClear placeholder="请选择账号">
            {options}
          </Select>
        </Form.Item>

        <Form.Item
          label="联系人"
          name="name"
          rules={[{ required: true, message: '请输入联系人姓名' }]}
        >
          <Input placeholder="请输入联系人姓名"></Input>
        </Form.Item>

        <Form.Item
          label="手机号"
          name="phone"
          rules={[{ required: true, message: '请输入联系人手机号' }, mobile]}
        >
          <Input placeholder="请输入联系人手机号"></Input>
        </Form.Item>
      </Form>
      <CommonLoading loading={loading} />
    </CommonModal>
  );
};

export default AddUserModal;
